package com.chijun.mform.process.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.chijun.mform.R;
import com.chijun.mform.create.mode.FormApproveProcess;
import com.chijun.mform.full.mode.ModeFormFullApprovePerson;
import com.chijun.mform.process.dapater.ApprovePersonResultAdapter;
import com.chijun.mform.process.IWaitLoadCompleteListener;
import com.chijun.mform.process.ModeServerFullData;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.b.c.recycler.BaseRecycler;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.server.MyObserver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 加载该表单的审批流程
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/12/27 12:12
 */
public class ViewLoadFullProcessData extends LinearLayout {

    ModeServerFullData serverFullData;
    public List<ModeFormFullApprovePerson> formApprovePersonList;
    IWaitLoadCompleteListener iWaitLoadProcessListener;
    BaseRecycler<ModeFormFullApprovePerson>  recycler;

    public ViewLoadFullProcessData(Context context, ModeServerFullData serverFullData, IWaitLoadCompleteListener iWaitLoadProcessListener) {
        super(context);
        this.serverFullData = serverFullData;
        this.iWaitLoadProcessListener = iWaitLoadProcessListener;
        init();
    }

    public ViewLoadFullProcessData(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setData(ModeServerFullData serverFullData, IWaitLoadCompleteListener iWaitLoadProcessListener){
        this.serverFullData = serverFullData;
        this.iWaitLoadProcessListener = iWaitLoadProcessListener;
        init();
    }


    private void init(){
        formApprovePersonList = new ArrayList<>();

        LinearLayout.inflate(getContext(), R.layout.view_load_full_process_data,this);
        recycler = findViewById(R.id.view_load_full_process_data_rec);

        Map<Long,FormApproveProcess> formApproveProcessMap = new HashMap<>();
        for (FormApproveProcess formApproveProcess : serverFullData.formApproveProcessList) formApproveProcessMap.put(formApproveProcess.id,formApproveProcess);
        recycler.setAdapter(formApprovePersonList,new ApprovePersonResultAdapter(formApprovePersonList,formApproveProcessMap));

//        LoadingDialog loadingDialog = new LoadingDialog(getContext());
//        loadingDialog.showLoading();

        //子线程加载审批人
        Observable.create(new ObservableOnSubscribe<ModeFormFullApprovePerson>() {
                    @Override
                    public void subscribe(ObservableEmitter<ModeFormFullApprovePerson> e) throws Exception {
                        for (ModeFormFullApprovePerson formApprovePerson : serverFullData.formApprovePeople) {
                            e.onNext(formApprovePerson);
                        }
                        e.onComplete();
                    }
                }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<ModeFormFullApprovePerson>() {
                    @Override
                    public void onNext(ModeFormFullApprovePerson formApprovePerson) {
//                        LogUtils.d("显示审批人员：" +formApprovePerson);
                        recycler.addDataOnTail(formApprovePerson);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        //返回给调用类一个加载完毕的回调
                        if (iWaitLoadProcessListener != null) iWaitLoadProcessListener.onComplete();
//                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
//                        loadingDialog.dismiss();
                        super.onError(e);
                        ErrorDialog errorDialog = new ErrorDialog(getContext(),e.getMessage());
                        errorDialog.show();
                    }
                });
    }


    /**
     * 添加一条审批人数据并刷新数据
     * @param personId 要添加在那个审批人下方的id
     * @param formFullApprovePerson 要添加的审批人
     */
    public void refreshAddData(long personId, ModeFormFullApprovePerson formFullApprovePerson){
        if (recycler != null) {
            if (personId == 1) {
                recycler.addDataOnTail(formFullApprovePerson);
            } else {

                List<ModeFormFullApprovePerson> defaultData = recycler.getDefaultData();
                if (defaultData != null) {
                    //recycler内没有数据将新数据添加在末尾
                    if (defaultData.isEmpty()) {
                        recycler.addDataOnTail(formFullApprovePerson);
                    } else {
                        boolean isFind = false;
                        //有数据时根据id查找该数据，如果查询到根据查询到的id添加到其上方 并返回查到到的标记isFind=true
                        for (int i = 0; i < recycler.getDefaultData().size(); i++) {
                            if (recycler.getDefaultData().get(i).id == personId) {
                                recycler.refreshData(i);
                                recycler.addDataOnFix(i,formFullApprovePerson);
                                isFind = true;
                                break;
                            }
                        }
                        //如果在原有数据中未查询到，将其添加到末尾
                        if (!isFind) {
                            recycler.addDataOnTail(formFullApprovePerson);
                        }
                    }
                } else {
                    LogUtils.e("添加审批流程失败，流程内的recycler没有初始数据！");
                }
            }
        }
    }

    public BaseRecycler<ModeFormFullApprovePerson> getRecycler() {
        return recycler;
    }
}
